package com.miracle9.game.dao;

import com.miracle9.game.entity.LevelInfo;
import com.miracle9.game.entity.User;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class UserServiceDao extends SqlOperating<User, Integer> {

    public void updateById(Integer id, String nickname, char sex, int photoId) {
        String hql = "update User set nickname=?,sex=?,photoId=? where id=?";
        Query query = q_CreateSql(hql, new Object[]{nickname, Character.valueOf(sex), Integer.valueOf(photoId), id});
        query.executeUpdate();
    }

    public void updatePasswordById(Integer id, String newPassword) {
        String hql = "update User set password=? where id=?";
        Query query = q_CreateSql(hql, new Object[]{newPassword, id});
        query.executeUpdate();
    }

    public void updateExpeGoldById(Integer id, int expeGold) {
        String hql = "update User set expeGold=? where id=?";
        Query query = q_CreateSql(hql, new Object[]{Integer.valueOf(expeGold), id});
        query.executeUpdate();
    }

    public void updateRechargeActivityById(Integer id, int rechargeActivity) {
        String hql = "update User set rechargeActivity=? where id=?";
        Query query = q_CreateSql(hql, new Object[]{Integer.valueOf(rechargeActivity), id});
        query.executeUpdate();
    }

    public int updateGameById(Integer id, int gameGold, int gameScore) {
        getSession().flush();
        getSession().clear();
        List<Integer> params = new ArrayList<>();
        String hql = "update User set gameGold = gameGold+?,gameScore=gameScore+? where id = ?";
        params.add(gameGold);
        params.add(gameScore);
        params.add(id);
        if (gameGold < 0) {
            hql = hql + " and gameGold>=?";
            params.add(-gameGold);
        }
        if (gameScore < 0) {
            hql = hql + " and gameScore>=?";
            params.add(-gameScore);
        }
        return q_CreateSql(hql, params.toArray()).executeUpdate();
    }
    public int updateGameById2(Integer id, int gameGold,int income,int income2) {
        getSession().flush();
        getSession().clear();
        List<Integer> params = new ArrayList<>();
        String hql = "update User set income=?,unincome=unincome+?,totalIncome=totalIncome+? where id = ?";
        params.add(income);
        params.add(income2);
        params.add(income2);
        params.add(id);
        return q_CreateSql(hql, params.toArray()).executeUpdate();
    }
    public int updateExpeByIdAndIf(Integer id, int expeGold, int expeScore) {
        getSession().clear();
        List params = new ArrayList();
        String hql = "update User set expeGold = expeGold+?,expeScore=expeScore+? where id = ?";
        params.add(Integer.valueOf(expeGold));
        params.add(Integer.valueOf(expeScore));
        params.add(id);
        if (expeGold < 0) {
            hql = hql + " and expeGold>=?";
            params.add(Integer.valueOf(-expeGold));
        }
        if (expeScore < 0) {
            hql = hql + " and expeScore>=?";
            params.add(Integer.valueOf(-expeScore));
        }
        return q_CreateSql(hql, params.toArray()).executeUpdate();
    }

    public void addUserScore(int id, int gameScore, int expeScore, double levelScore) {
        q_CreateSql("update User set gameScore=gameScore+?,expeScore = expeScore+?,levelScore=levelScore+? where id = ?", new Object[]{Integer.valueOf(gameScore), Integer.valueOf(expeScore), Double.valueOf(levelScore), Integer.valueOf(id)}).executeUpdate();
    }

    public void addUserLevel(int id) {
        q_CreateSql("update User set level=level+1 where id = ?", new Object[]{Integer.valueOf(id)}).executeUpdate();
    }

    public void updateUserLevel(int id,int level) {
        q_CreateSql("update User set level=? where id = ?", new Object[]{level, id}).executeUpdate();
    }

    public void updateLastDeskIdById(Integer userId, int deskId) {
        q_CreateSql("update User set lastDeskId=? where id = ?", new Object[]{Integer.valueOf(deskId), userId}).executeUpdate();
    }

    public void updateStatus(int id, int status) {
        q_CreateSql("update User set status=? where id = ?", new Object[]{Integer.valueOf(status), Integer.valueOf(id)}).executeUpdate();
    }

    public boolean updateGameGoldById(int id, int gold) {
        getSession().clear();
        int cnt = q_CreateSql("update User set gameGold=gameGold+? where id = ?", new Object[]{Integer.valueOf(gold), Integer.valueOf(id)}).executeUpdate();

        return cnt > 0;
    }

    public void updateQuestionInfoById(int id, String question, String answer, String phone, String card) {
        q_CreateSql("update User set question=?,answer=?,phone=?,card=? where id = ?", new Object[]{question, answer, phone, card, Integer.valueOf(id)}).executeUpdate();
    }

    public void updateLevelInfoById(int id, LevelInfo levelInfo) {
        q_CreateSql("update User set level=?,levelScore=? where id = ?", new Object[]{Integer.valueOf(levelInfo.getLevel()), Double.valueOf(levelInfo.getMinScore()), Integer.valueOf(id)}).executeUpdate();
    }

    public List<Integer> ifGetId(String date, int type) {
        Query query = null;
        if (type == 0) {
            query = q_CreateSql("select id from User where promoterId=0 and registDate like ?", new Object[]{date + "%"});
        } else if (type == 1) {
            query = q_CreateSql("select id from User where promoterId!=0 and registDate like ?", new Object[]{date + "%"});
        } else {
            query = q_CreateSql("select id from User where registDate like ?", new Object[]{date + "%"});
        }
        return query.list();
    }

    public int getQuantityByDateAndIds(List<Integer> registUsers, String date) {
        Query query = getSession().createQuery("select count(*) from User where loginDate like ? and id in(:ids)");
        query.setParameter(0, date + "%");
        query.setParameterList("ids", registUsers);
        return Integer.valueOf(query.uniqueResult().toString()).intValue();
    }

    public void updateOverflow(int userId, int i) {
        q_CreateSql("update User set overflow = ? where id=?", new Object[]{Integer.valueOf(i), Integer.valueOf(userId)}).executeUpdate();
    }

    public void updateShutupStatus(int id, int type) {
        q_CreateSql("update User set shutupStatus = ? where id=?", new Object[]{Integer.valueOf(type), Integer.valueOf(id)}).executeUpdate();
    }

    public void updateNoActive(String date) {
        String hql = "update User set status=1 where (loginDate !='' and loginDate<? and status=0) or (loginDate='' and registDate<? and status=0)";
        q_CreateSql(hql, new Object[]{date, date}).executeUpdate();
    }

    public long getSumGameGoldByPromoterId_0() {
        Object sum = q_CreateSql("select sum(gameGold) from User where promoterId=0", new Object[0]).uniqueResult();
        if (sum == null) {
            return 0L;
        }
        return ((Long) sum).longValue();
    }

    public long getSumGameGoldByPromoterId(int promoterId) {
        Object sum = q_CreateSql("select sum(gameGold) from User where promoterId=? and status in (0,1)", new Object[]{Integer.valueOf(promoterId)}).uniqueResult();
        if (sum == null) {
            return 0L;
        }
        return ((Long) sum).longValue();
    }

    public long SumGameGoldByPromoterId(int promoterId, String searchWord) {
        Object sum = q_CreateSql("select sum(gameGold) from User where promoterId=? and status in (0,1) and username like ?", new Object[]{Integer.valueOf(promoterId),
                "%" + searchWord + "%"}).uniqueResult();
        if (sum == null) {
            return 0L;
        }
        return ((Long) sum).longValue();
    }

    public void updateExpiryNum(int userId, int expiryNum) {
        q_CreateSql("update User set expiryNum = ? where id=?", new Object[]{Integer.valueOf(expiryNum), Integer.valueOf(userId)}).executeUpdate();
    }

    public void updateExpiryNum(int userId, int expiryNum, String phone) {
        q_CreateSql("update User set gameGold=gameGold-?,expiryNum = ?, phone=? where id=?", new Object[]{expiryNum, Integer.valueOf(expiryNum), phone, Integer.valueOf(userId)}).executeUpdate();
    }

    public void updatePayMoney(int userId, int payMoney) {
        q_CreateSql("update User set payMoney = ? where id=?", new Object[]{Integer.valueOf(payMoney), Integer.valueOf(userId)}).executeUpdate();
    }

    public void evict(User user) {
        getSession().evict(user);
    }

    public int getQuantity() {
        return q_CreateSqlInt("select count(*) from User", new Object[0]);
    }

    public void updateLoginDateById(int id, String loginDate, int language) {
        q_Update("update User set loginDate=?,language=? where id=?", new Object[]{loginDate, language, Integer.valueOf(id)});
    }

    public void deleteByDate(String date) {
        q_CreateSql("delete from UserTenMinScore where startTime<?", new Object[]{date}).executeUpdate();
    }

    public List<Object[]> returnList_3(String hql, String startDate, String endDate) {
        SQLQuery query = null;
        query = s_CreateSql(hql, new Object[]{startDate, endDate});
        return query.list();
    }

    public List<Object[]> returnList_4(String hql, String username, String startDate, String endDate) {
        SQLQuery query = null;
        query = s_CreateSql(hql, new Object[]{username, startDate, endDate});
        return query.list();
    }

    public void deleteByDateBlurry(String date) {
        q_CreateSql("delete from UserTenMinScore where endTime like ?", new Object[]{date + "%"}).executeUpdate();
    }

    @Cacheable(value = {"springCache"}, key = "'userList'")
    public List<User> getUsers() {
        return q_CreateSqlList("from User", new Object[0]);
    }

    public List<User> getUserByIdLtNLastUserId(int nLastUserId) {
        return q_CreateSqlList("from User where id > " + nLastUserId, new Object[0]);
    }

    public List<User> getUsersOrderByLevel() {
        Query query = q_CreateSql("from User order by level desc limit 0,10", new Object[0]);
        query.setMaxResults(10);
        return query.list();
    }

    public List<User> getUsersOrderByGameGold() {
        Query query = q_CreateSql("from User order by gameGold desc limit 0,10", new Object[0]);
        query.setMaxResults(10);
        return query.list();
    }

    public int getSumYaGoldByUid(int nUserId) {
        String hql = "select sum(yaGold) from UserTenMinScore where userId=" + nUserId;

        Object sum = q_CreateSql(hql, new Object[0]).uniqueResult();
        if (sum == null) {
            return 0;
        }
        return ((Number) sum).intValue();
    }

    public void updateWarningStatus(int id, int warningStatus) {
        q_CreateSql("update User set warningStatus=? where id = ?", new Object[]{Integer.valueOf(warningStatus), Integer.valueOf(id)}).executeUpdate();
    }

    public long getSumGameGold() {
        Object sum = q_CreateSql("select sum(gameGold) from User", new Object[0]).uniqueResult();
        if (sum == null) {
            return 0L;
        }
        return ((Long) sum).longValue();
    }

    public int getQuantityByPromoterId_0() {
        return q_CreateSqlInt("select count(*) from User where promoterId = 0", new Object[0]);
    }

    public int getQuantityByPromoterId() {
        return q_CreateSqlInt("select count(*) from User where promoterId != 0", new Object[0]);
    }

    public void updateSafeBox(int userId, int safeBox) {
        q_CreateSql("update User set safeBox = ? where id=?", new Object[]{Integer.valueOf(safeBox), Integer.valueOf(userId)}).executeUpdate();
    }

    public void updateSafeBoxPwd(int userId, String safeBoxPwd) {
        q_CreateSql("update User set security = ? where id=?", new Object[]{Integer.valueOf(safeBoxPwd), Integer.valueOf(userId)}).executeUpdate();
    }

    public void updateUserControl(int id, int controlType, int controlExpire, int maxGold, int fishControlValue) {
        q_CreateSql("update User set controlType=?,controlExpire=?,maxGold=?,fishControlValue=? where id=?", new Object[]{controlType, controlExpire, maxGold, fishControlValue, id}).executeUpdate();
    }

    public void updateUserControl(int userId, int usercontrol) {
        usercontrol--;
        int userc = 0;
        if (usercontrol <= 0) {
            userc = 0;
        } else if (usercontrol > 0 && usercontrol <= 3) {
            userc = 1000 + 100 * usercontrol;
        } else if (usercontrol > 3 && usercontrol < 10) {
            userc = 1000 - 10 * (usercontrol - 3);
        } else if (usercontrol >= 10) {
            userc = 1000 - 20 * usercontrol;
        }
        q_CreateSql("update User set usercontrol = ? where id=?", new Object[]{userc, userId}).executeUpdate();
    }

    public int addBoxGameGold(Integer id, int boxGameGold) {
        getSession().flush();
        getSession().clear();
        List params = new ArrayList();
        String hql = "update User set boxGameGold = boxGameGold+? where id = ?";
        params.add(Integer.valueOf(boxGameGold));
        params.add(id);
        if (boxGameGold < 0) {
            hql = hql + " and boxGameGold>=?";
            params.add(Integer.valueOf(-boxGameGold));
        }
        return q_CreateSql(hql, params.toArray()).executeUpdate();
    }

}
